package org.example.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 异步处理类
 *
 * @author Maple
 * @date 2024-01-17
 */
@Slf4j
@Component
public class AsyncUtil {

    private static AsyncBean asyncBean;

    private static final AtomicInteger RUNNING_COUNT =  new AtomicInteger(0);


    @Autowired AsyncUtil (AsyncBean asyncBean) {
        AsyncUtil.asyncBean = asyncBean;
    }

    public static void async (Runnable r) {
        try {

            if (isBusy(RUNNING_COUNT.incrementAndGet())){

                // TODO 任务过多想怎么处理，目前是给主线程执行
                r.run();

            } else asyncBean.doAsync(r);

        } finally {
            RUNNING_COUNT.decrementAndGet();
        }
    }

    public static void countDownLatch (List<? extends Runnable> tasks) throws InterruptedException {

        if(null == tasks || tasks.isEmpty()) return;

        CountDownLatch latch = new CountDownLatch(tasks.size());

        for (Runnable task : tasks) {
            async(()-> {
                try {
                    task.run();
                } finally {
                    latch.countDown();
                }
            });
        }

        latch.await();

    }

    public static boolean isBusy (int count) {
        checkAlarm(count);
        return count > 300;
    }

    private static void checkAlarm(int count) {
        if(count > 600) log.error("AsyncUtil异步任务过载！");
        else if(count > 300) log.error("AsyncUtil异步任务繁重！");
    }

}
